﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Management;
using System.Drawing.Printing;

namespace app.Common
{
    public class Printer_Helper
    {
        string m_PrinterName = "";
        UInt32 m_state;

        public string Printer_Name
        {
            set { this.m_PrinterName = value; }
        }

        public UInt32 PrinterState
        {
            get
            {
                IsPrinterReady();
                return m_state;
            }
        }

        public ManagementObjectCollection Get_PriterList() //PrinterSettings.StringCollection Get_PriterList()
        {
            ManagementScope scope = new ManagementScope(@"\root\cimv2");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Printer");
            return searcher.Get();
            //return PrinterSettings.InstalledPrinters;
        }
        private ManagementObjectCollection Get_Priter(string PrinterName)
        {
            try
            {
                ManagementScope scope = new ManagementScope(@"\root\cimv2");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Printer where Name ='" + PrinterName + "'");
                return searcher.Get();
            }
            catch
            { 
            }
            return null;
        }

        //bool IsPrinterReady(String printerName)
        //{
        //    string strPrinterName = string.Empty;
        //    foreach (ManagementObject printer in Get_PriterList())
        //    {
        //        strPrinterName = printer["Name"].ToString();
        //        if (strPrinterName.ToLower() == printerName.ToLower()) //ps.PrinterName
        //        {
        //            if (printer["WorkOffline"].ToString().ToLower().Equals("true"))
        //            {
        //                return false;
        //            }

        //            m_state = Convert.ToUInt32(printer["PrinterState"]);
        //            m_ErrMsg = PrinterStatus_Msg.GetPrinterStatusMsg(m_state);

        //            return m_state == 0;
        //        }
        //    }

        //    return false;

        //}

        public bool IsPrinterReady()
        {
            ManagementScope scope = new ManagementScope(@"\root\cimv2");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Printer where Name ='" + m_PrinterName + "'");

            ManagementObjectCollection printer_list = searcher.Get();
            if (printer_list.Count == 0)
                return false;

            foreach (ManagementObject printer in printer_list)
            {
                if (printer["WorkOffline"].ToString().ToLower().Equals("true"))
                {
                    return false;
                }

                m_state = Convert.ToUInt32(printer["PrinterState"]);
                m_ErrMsg = PrinterStatus_Msg.GetPrinterStatusMsg(m_state);
            }

            return m_state == 0;

        }

        //public bool IsDefaultPrinterReady()
        //{
        //    PrinterSettings ps = new PrinterSettings();

        //    string DefaultPrinterName = "";
        //    foreach (String printer in PrinterSettings.InstalledPrinters)
        //    {
        //        ps.PrinterName = printer.ToString();
        //        if (ps.IsDefaultPrinter)
        //        {
        //            DefaultPrinterName = printer.ToString();
        //            break;
        //        }
        //    }

        //    return IsPrinterReady(DefaultPrinterName);

        //}

        //-------------
        string m_ErrMsg = "";

        public string Error_Msg
        {
            get
            {
                return m_ErrMsg;
            }
        }


        Image LoadImage(string name)
        {
            Image img = null;
            try
            {
                string filename = @"" + name + ".JPG";
                img = Image.FromFile(filename);
            }
            catch
            {

            }

            return img;
        }

        public Image Resize(Image img, float percentage)
        {
            //lấy kích thước ban đầu của bức ảnh
            int originalW = img.Width;
            int originalH = img.Height;

            //tính kích thước cho ảnh mới theo tỷ lệ đưa vào
            int resizedW = (int)(originalW * percentage);
            int resizedH = (int)(originalH * percentage);

            //tạo 1 ảnh Bitmap mới theo kích thước trên
            Bitmap bmp = new Bitmap(resizedW, resizedH);
            //tạo 1 graphic mới từ Bitmap
            Graphics graphic = Graphics.FromImage((Image)bmp);
            //vẽ lại ảnh ban đầu lên bmp theo kích thước mới
            graphic.DrawImage(img, 0, 0, resizedW, resizedH);
            //giải phóng tài nguyên mà graphic đang giữ
            graphic.Dispose();
            //return the image
            return (Image)bmp;
        }

        public bool InHoaDonNapTien(ref string PrintString, ref string Header, Image logo, DateTime Thoidiem, string TenNV, string MaKH, string Hoten, string LoaiThe, string SoTienNap, string SoTienKD, string SoTienTraLai)
        {
            try
            {
                string sPrint = "";
                string sHeader = "";

                PrintByDriver prn = new PrintByDriver();
                logo = Resize(logo, 0.4F);
                if (logo != null)
                {
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sPrint += sHeader + "\r\n";
                }

                sHeader = sHeader + Header.PadLeft((Header.Length + 30) / 2, ' ') + "\r\n";

                sPrint += "\r\n";
                if (TenNV.Length > 23)
                {
                    string[] strTen = TenNV.Split(' ');
                    TenNV = "";
                    string strTemp = "";
                    int i = 0;
                    for (i = 0; i < strTen.Length - 1; i++)
                    {
                        if (strTemp == "")
                            strTemp = strTen[i];
                        else
                            strTemp = strTemp + " " + strTen[i];

                        if (strTemp.Length <= 23)
                            TenNV = strTemp;
                        else
                            break;
                    }

                    strTemp = "";
                    for (int j = i; j < strTen.Length; j++)
                    {
                        if (strTemp == "")
                            strTemp = strTen[j];
                        else
                            strTemp = strTemp + " " + strTen[j];
                    }
                    TenNV = TenNV + "\r\n" + strTemp.PadLeft(32, ' ');
                }

                sPrint += " Thời Điểm: " + Thoidiem.ToString("dd/MM/yyyy - HH:mm").PadLeft(32 - " Thời Điểm: ".Length) + "\r\n";
                sPrint += " Tên NV: " + TenNV + "\r\n";

                sPrint += "\r\n";
                sPrint += "\r\n";

                sPrint += " Mã KH: " + MaKH.PadLeft(32 - " Mã KH: ".Length) + "\r\n";
                sPrint += " Tên KH: " + Hoten.PadLeft(32 - " Tên KH: ".Length) + "\r\n";

                sPrint += "\r\n";
                sPrint += "\r\n";

                sPrint += " Số Tiền Nạp: " + SoTienNap.PadLeft(32 - " Số Tiền Nạp: ".Length) + "\r\n";
                sPrint += " Số Tiền Khách Đưa: " + SoTienKD.PadLeft(32 - " Số Tiền Khách Đưa: ".Length) + "\r\n";
                sPrint += " Số Tiền Trả Lại: " + SoTienTraLai.PadLeft(32 - " Số Tiền Trả Lại: ".Length) + "\r\n";


                PrintString = sPrint;
                Header = sHeader;

                prn.PrinterName = m_PrinterName;
                prn.Print(logo, sHeader, sPrint);


                return true;
            }
            catch { return false; }
        }

        public bool InHoaDonGoiMon(ref string PrintString, ref string Header, string MaHoaDon, string TenNV, string TenBan, DateTime GioIn, System.Data.DataTable tblChiTietHoaDon, string GhiChu)
        {
            bool retval_bool;
            try
            {
                string sPrint = "";
                string sHeader = "";
                string sObject = "";

                PrintByDriver prn = new PrintByDriver();

                Image logo = LoadImage("logo");
                logo = null;
                if (logo != null)
                {
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sPrint += sHeader + "\r\n";
                }
                sHeader = sHeader + Header.PadLeft((Header.Length) / 2, ' ') + "\r\n";
                sObject += "\r\n" + " Bàn: " + TenBan + "\r\n";
                sPrint += "\r\n";
                sPrint += "\r\n";
                sPrint += "\r\n";
                sPrint += "\r\n";
                sPrint += " NV: " + TenNV + "\r\n";
                sPrint += " STT: " + MaHoaDon.Substring(1, 4) + "\r\n";
                sPrint += " -------------------------------\r\n";
                sPrint += " Mã HĐ: " + MaHoaDon + "\r\n";
                sPrint += " Giờ : " + GioIn.ToString("dd/MM/yyyy HH:mm") + "\r\n";
                sPrint += " -------------------------------\r\n";
                string header = " STT Tên SP                   Sl\r\n";
                int leng = header.Length;
                string printstring, tempstring;
                int index;

                for (int i = 0; i < tblChiTietHoaDon.Rows.Count; i++)
                {
                    printstring = " ";

                    index = header.IndexOf("STT");
                    //tempstring = tblChiTietHoaDon.Rows[i][0].ToString();
                    tempstring = (i + 1).ToString();
                    tempstring = "".PadLeft(index) + tempstring;
                    printstring += tempstring;

                    index = header.IndexOf("Tên SP");
                    tempstring = tblChiTietHoaDon.Rows[i][1].ToString();
                    tempstring = tempstring.Length > 22 ? tempstring.Substring(0, 22) : tempstring;
                    tempstring = "".PadLeft(index - printstring.Length) + tempstring;
                    //tempstring = "".PadLeft(index) + tempstring;
                    printstring += tempstring;

                    index = header.IndexOf("Sl");
                    tempstring = decimal.Parse(tblChiTietHoaDon.Rows[i][2].ToString(), System.Globalization.NumberStyles.Any).ToString();
                    tempstring = tempstring.Length > 3 ? tempstring.Substring(0, 3) : tempstring;
                    tempstring = "".PadLeft(index - printstring.Length) + tempstring.PadLeft(2);

                    printstring += tempstring;
                    sPrint += printstring;
                    sPrint += "\r\n";
                }

                sPrint += " -------------------------------\r\n";

                if (GhiChu.Trim() != "")
                {
                    sPrint += " Ghi Chú: " + "\r\n";
                    sPrint += controlString(GhiChu, 1, 30);
                }

                PrintString = sPrint;
                Header = sHeader;

                prn.PrinterName = m_PrinterName;
                prn.PrintBillMoi(logo, sHeader, sPrint, sObject, 10);

                retval_bool = true;
            }
            catch (Exception ex)
            {
                //m_ErrMsg = ex.Message;
                retval_bool = false;
            }
            return retval_bool;
        }
        public bool InHoaDonThanhToan(ref string PrintString, ref string Header, string MaHoaDon, string TenNV, string TenBan, DateTime GioIn, System.Data.DataTable tblChiTietHoaDon, string GhiChu, decimal TienGiamGia, decimal ThanhTien, decimal TienKhachDua, decimal TienThoiLai)
        {
            bool retval_bool;
            try
            {
                string sPrint = "";
                string sHeader = "";
                string sObject = "";

                PrintByDriver prn = new PrintByDriver();

                Image logo = LoadImage("logo");
                if (logo != null)
                {
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sPrint += sHeader + "\r\n";
                }
                sHeader = sHeader + Header.PadLeft((Header.Length) / 2, ' ') + "\r\n";
                sObject += "\r\n" + " Bàn: " + TenBan + "\r\n";
                sPrint += "\r\n";
                sPrint += "\r\n";
                sPrint += "\r\n";
                sPrint += "\r\n";
                sPrint += " NV: " + TenNV + "\r\n";
                sPrint += " STT: " + MaHoaDon.Substring(1, 4) + "\r\n";
                sPrint += " -------------------------------\r\n";
                sPrint += " Mã HĐ: " + MaHoaDon + "\r\n";
                sPrint += " Giờ : " + GioIn.ToString("dd/MM/yyyy HH:mm") + "\r\n";
                sPrint += " -------------------------------\r\n";
                string header = " STT Tên SP       Sl  Thành Tiền\r\n";
                int leng = header.Length;
                string printstring, tempstring;
                int index;

                for (int i = 0; i < tblChiTietHoaDon.Rows.Count; i++)
                {
                    printstring = " ";

                    index = header.IndexOf("STT");
                    tempstring = (i + 1).ToString();
                    tempstring = "".PadLeft(index) + tempstring;
                    printstring += tempstring;

                    index = header.IndexOf("Tên SP");
                    tempstring = tblChiTietHoaDon.Rows[i][1].ToString();
                    tempstring = tempstring.Length > 22 ? tempstring.Substring(0, 22) : tempstring;
                    tempstring = "".PadLeft(index - printstring.Length) + tempstring;
                    printstring += tempstring;

                    index = header.IndexOf("Sl");
                    tempstring = decimal.Parse(tblChiTietHoaDon.Rows[i][2].ToString(), System.Globalization.NumberStyles.Any).ToString();
                    tempstring = tempstring.Length > 3 ? tempstring.Substring(0, 3) : tempstring;
                    tempstring = "".PadLeft(index - printstring.Length) + tempstring.PadLeft(2);

                    index = header.IndexOf("Thành Tiền");
                    tempstring = decimal.Parse(tblChiTietHoaDon.Rows[i][3].ToString(), System.Globalization.NumberStyles.Any).ToString();
                    tempstring = tempstring.Length > 8 ? tempstring.Substring(0, 8) : tempstring;
                    tempstring = "".PadLeft(index - printstring.Length) + tempstring.PadLeft(2);

                    printstring += tempstring;
                    sPrint += printstring;
                    sPrint += "\r\n";
                }

                sPrint += " -------------------------------\r\n";
                sPrint += " Thành tiền: " + String.Format("{0:0,0 VNĐ}",ThanhTien) + "\r\n";
                sPrint += " Giảm giá: " + String.Format("{0:0,0 VNĐ}", TienGiamGia) + "\r\n";
                sPrint += " Tiền khách đưa: " + String.Format("{0:0,0 VNĐ}", TienKhachDua) + "\r\n";
                sPrint += " Tiền thối lại: " + String.Format("{0:0,0 VNĐ}", TienThoiLai) + "\r\n";
                PrintString = sPrint;
                Header = sHeader;

                prn.PrinterName = m_PrinterName;
                prn.PrintBillMoi(logo, sHeader, sPrint, sObject, 10);

                retval_bool = true;
            }
            catch (Exception ex)
            {
                //m_ErrMsg = ex.Message;
                retval_bool = false;
            }
            return retval_bool;
        }
        public bool InHoaDon(ref string PrintString, ref string Header, string MaHoaDon, string TenKhachHang, string SDT, string DiaChi, string ThoiGianGiaoHang, string NVGiaoHang, long TongDiemTichLuy, string TenNV, DateTime GioIn, System.Data.DataTable tblChiTietHoaDon, string SoPhieu, decimal TienTong, decimal TienThanhToan, decimal TienGiamGia, decimal TienKhachDua, decimal TienThoi, string TenBan, bool IsTamTinh)
        {
            bool retval_bool;
            try
            {
                string sPrint = "";
                string sHeader = "";
                decimal tong = 0;

                PrintByDriver prn = new PrintByDriver();
                Image logo = LoadImage("logo");
                
                if (logo != null)
                {
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sHeader = sHeader + "  \r\n";
                    sPrint += sHeader + "\r\n";
                }
                sHeader = sHeader + Header.PadLeft((Header.Length + 30) / 2, ' ') + "\r\n";

                sPrint += "\r\n";
                if (TenNV.Length > 23)
                {
                    string[] strTen = TenNV.Split(' ');
                    TenNV = "";
                    string strTemp = "";
                    int i = 0;
                    for (i = 0; i < strTen.Length - 1; i++)
                    {
                        if (strTemp == "")
                            strTemp = strTen[i];
                        else
                            strTemp = strTemp + " " + strTen[i];

                        if (strTemp.Length <= 23)
                            TenNV = strTemp;
                        else
                            break;
                    }

                    strTemp = "";
                    for (int j = i; j < strTen.Length; j++)
                    {
                        if (strTemp == "")
                            strTemp = strTen[j];
                        else
                            strTemp = strTemp + " " + strTen[j];
                    }
                    TenNV = TenNV + "\r\n" + strTemp.PadLeft(32, ' ');
                }
                sPrint += " Số liên: " + SoPhieu.PadLeft(32 - " Số liên: ".Length) + "\r\n";
                sPrint += " Giờ In: " + GioIn.ToString("dd/MM/yyyy - HH:mm:ss").PadLeft(32 - " Giờ   : ".Length) + "\r\n";
                sPrint += " Mã HĐ : " + MaHoaDon + "\r\n";
                sPrint += " Tên NV: " + TenNV + "\r\n";
                sPrint += " Bàn: " + TenBan + "\r\n";
                //sPrint += " -------------------------------\r\n";
                sPrint += " <----------------------------->\r\n";
                sPrint += " STT Tên hàng     S.lg   T.Tiền   \r\n";
                sPrint += " -------------------------------\r\n";
                string header = " STT Tên SP     S.lg  T.Tiền     \r\n";
                int leng = header.Length;
                //string sothutu, tenhangban, soluong, thanhtien;
                string printstring = "", tempstring = "";
                decimal subtempIntstring;
                int index;
                decimal Soluong = 0, DonGia = 0, Cong = 0, KM, ConLai = 0;

                ///--------------------------------------------------------------------
                ///Filter for != 0% và !=100%
                for (int i = 0; i < tblChiTietHoaDon.Rows.Count; i++)
                {
                    printstring = " ";

                    index = header.IndexOf("STT");
                    tempstring = tblChiTietHoaDon.Rows[i][0].ToString() + ".";
                    tempstring = "".PadLeft(index - 1) + tempstring;
                    printstring += tempstring;

                    index = header.IndexOf("Tên SP");
                    tempstring = tblChiTietHoaDon.Rows[i][2].ToString();
                    tempstring = tempstring.Length > 12 ? tempstring.Substring(0, 12) : tempstring;
                    tempstring = "".PadLeft(index - printstring.Length - 1) + tempstring;
                    printstring += tempstring;

                    index = header.IndexOf("S.lg");
                    Soluong = int.Parse(tblChiTietHoaDon.Rows[i][3].ToString(), System.Globalization.NumberStyles.Any);
                    tempstring = Soluong.ToString();
                    tempstring = tempstring.Length > 3 ? tempstring.Substring(0, 3) : tempstring;
                    tempstring = "".PadLeft(index - printstring.Length + 1) + tempstring.PadLeft(4);
                    printstring += tempstring;

                    DonGia = int.Parse(tblChiTietHoaDon.Rows[i][4].ToString(), System.Globalization.NumberStyles.Any);

                    index = header.IndexOf("T.Tiền");
                    Cong = DonGia * Soluong;
                    tempstring = Cong.ToString("N0");
                    //tempstring = tempstring.Length > 3 ? tempstring.Substring(0, 3) : tempstring;
                    tempstring = "".PadLeft(32 - printstring.Length - tempstring.Length) + tempstring;
                    printstring += tempstring;

                    //sPrint += tblChiTietThu.Rows[i]["sothutu"].ToString();
                    //sPrint += "\t" + tblChiTietThu.Rows[i]["tenhangban"].ToString();
                    //sPrint += "\t" + tblChiTietThu.Rows[i]["soluong"].ToString();
                    //sPrint += "\t" + tblChiTietThu.Rows[i]["thanhtien"].ToString();
                    sPrint += printstring;
                    sPrint += "\r\n";

                    printstring = "";
                    tempstring = " Cộng :";
                    printstring += tempstring + Cong.ToString("N0").PadLeft(32 - tempstring.Length) + "\r\n";
                }

                sPrint = sPrint + " -------------------------------\r\n";
                //Command 26/03/2013
                //sPrint += "\r\n";
                printstring = "";
                //printstring += tempstring + TienNapThe.ToString("N0").PadLeft(32 - tempstring.Length) + "\r\n";

                tempstring = " Tổng cộng: ";
                printstring += tempstring + TienTong.ToString("N0").PadLeft(32 - tempstring.Length) + "\r\n";

                if (!IsTamTinh)
                {
                    tempstring = " Khuyến mãi: ";
                    printstring += tempstring + TienGiamGia.ToString("N0").PadLeft(32 - tempstring.Length) + "\r\n";

                    tempstring = " Tiền thanh toán: ";
                    printstring += tempstring + TienThanhToan.ToString("N0").PadLeft(32 - tempstring.Length) + "\r\n";
                }
                //printstring += " -------------------------------\r\n";

                //printstring = " ";
                //Command 26/03/2013
                //tempstring = " Tiền khách đưa: ";
                //printstring += tempstring + TienKhachDua.ToString("N0").PadLeft(32 - tempstring.Length) + "\r\n";

                //Command 26/03/2013
                //printstring = " ";
                //tempstring = " Tiền hoàn lại:  ";
                //printstring += tempstring + TienThoi.ToString("N0").PadLeft(32 - tempstring.Length) + "\r\n";

                sPrint += printstring;
                //sPrint = sPrint + "\r\n";
                if (TenKhachHang != "" && SDT != "" && DiaChi != "")
                {
                    sPrint += " -------------------------------\r\n";
                    sPrint += " Tên KH: " + TenKhachHang + "\r\n";
                    sPrint += " SĐT: " + SDT + "\r\n";
                    sPrint += " Địa chỉ: \r\n" + controlString(" " + DiaChi, 1, 31) + " \r\n";
                }
                //Command 26/03/2013
                //sPrint += " Thời gian: " + ThoiGianGiaoHang + "\r\n";
                //sPrint += " NV Giao Hàng: " + NVGiaoHang + "\r\n";

                //Command 26/03/2013
                //sPrint += " Tổng điểm tích lũy : " + TongDiemTichLuy.ToString("N0") + "\r\n";
                sPrint += " -------------------------------\r\n";
                sPrint += " HẸN GẶP LẠI QUÝ KHÁCH\r\n";
                //sPrint += " Lưu ý:\r\n";

                PrintString = sPrint;
                Header = sHeader;

                prn.PrinterName = m_PrinterName;
                prn.Print(logo, sHeader, sPrint);

                retval_bool = true;
            }
            catch (Exception ex)
            {
                //m_ErrMsg = ex.Message;
                retval_bool = false;
            }
            return retval_bool;
        }
        private string controlString(string text, int startindex, int maxchar)
        {
            string[] s = text.Split(' ');
            int count = 1;
            string re = "";
            count = startindex;

            foreach (string a in s)
            {
                if (a != "")
                {
                    count += a.Length;
                    if (count < maxchar)
                    {
                        if (count == 0)
                            re += a;
                        else
                        {
                            re += " " + a;
                            count++;
                        }
                    }
                    else
                    {
                        re += Environment.NewLine;
                        re += " " + a;
                        count = a.Length;
                    }
                }
                else count = 0;
            }

            return re;
        }

    }

}
